import { defineStore } from 'pinia'
import { ref, computed, reactive } from 'vue'

export const useUserStore = defineStore(
    //id
    'user',
    //定义初始值
    () => {
        //定义token
        const token = ref('')
        //获取token
        const getToken = computed(() => token.value)
        //保存token
        const saveToken = (t) => {
            token.value = t
        }
        //定义user信息
        const user = reactive({
            uname:'',
            uimage:'',
            uid:0,
            cartCount:0,
        })
        //保存user信息
        const saveUser = (myUser) => {
            user.uid=myUser.uid
            user.uname=myUser.uname
            user.uimage=myUser.uimage
        }
        //要返回token，因为持久化token常量
        return { getToken, saveToken, token, user, saveUser }
    },
    //持久化
    {
        persist: {
            //开启持久化
            enabled: true,
            //策略
            strategies: [
                {
                    //持久化key名称
                    key: 'user-info',
                    //存储方式：localStorage或者sessionStorage
                    storage: localStorage,
                    //指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态，undefined 或 null 表示持久化整个 state
                    //paths: ['token']
                }
            ]
        }
    }
)